//
//  XGMainViewController.swift
//  TodayNews
//
//  Created by monkey on 2020/2/3.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import SwiftTheme

// MARK: - XGMainViewController

class XGMainViewController: UITabBarController
{
    // MARK: 控制器生命周期方法
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        // KVC替换tabBar
        setValue(XGTabBar(), forKey: "tabBar")
        NotificationCenter.default.addObserver(self, selector: #selector(switchThemeNotification(noti:)), name: TodayNews_SwitchTheme_Notification, object: nil)
        // 设置外观样式
        setUpAppearance()
        // 添加子控制器
        addAllChildViewControllers()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: 私有扩展

private extension XGMainViewController
{
    @objc func switchThemeNotification(noti: Notification) -> Void
    {
        let imageName = TodayNewsThemeManager.shared.currentTheme == .day ? "navigation_background" : "navigation_background_night"
        let navBar = UINavigationBar.appearance(whenContainedInInstancesOf: [XGMainViewController.self])
        navBar.setBackgroundImage(UIImage(named: imageName), for: .default)
    }
    
    /// 设置全局样式
    func setUpAppearance() -> Void
    {
        // 设置渲染色
        let tabBar = UITabBar.appearance(whenContainedInInstancesOf: [XGMainViewController.self])
        tabBar.theme_tintColor = "colors.tabbar_tint"
        tabBar.theme_barTintColor = "colors.cell_background"
        
        let navBar = UINavigationBar.appearance(whenContainedInInstancesOf: [XGMainViewController.self])
        navBar.isTranslucent = true
        navBar.theme_tintColor = "colors.navigationBar_tint"
        navBar.setBackgroundImage(UIImage(named: "navigation_background"), for: .default)
        navBar.theme_titleTextAttributes = ThemeStringAttributesPicker(keyPath: "colors.navigationBar_tint", map: { (colorString) -> [NSAttributedString.Key : Any]? in
            guard let colorString = colorString as? String else {
                return nil
            }
            
            return [NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexadecimal: colorString)]
        })
        
        let tabBarItem = UITabBarItem.appearance(whenContainedInInstancesOf: [XGMainViewController.self])
        tabBarItem.setTitleTextAttributes([.font: UIFont.systemFont(ofSize: 13)], for: .normal)
    }
    
    /// 添加所有子控制器
    func addAllChildViewControllers() -> Void
    {
        addChilViewController(XGHomeViewController(), title: "首页", imageName: "images.tabBar_home_normal", SelectedImageName: "images.tabBar_home_selected")
        addChilViewController(XGVideoViewController(), title: "视频", imageName: "images.tabBar_video_normal", SelectedImageName: "images.tabBar_video_selected")
        addChilViewController(XGHuoShanViewController(), title: "火山", imageName: "images.tabBar_huoshan_normal", SelectedImageName: "images.tabBar_huoshan_selected")
        addChilViewController(XGMineViewController(), title: "我的", imageName: "images.tabBar_mine_normal", SelectedImageName: "images.tabBar_mine_selected")
    }
    
    /// 添加子控制器
    /// - Parameters:
    ///   - viewController: 控制器
    ///   - title: 标题
    ///   - imageName: 图片名
    ///   - SelectedImageName: 选中图片名
    func addChilViewController(_ viewController: UIViewController, title: String, imageName: String, SelectedImageName: String) -> Void
    {
        viewController.tabBarItem.theme_image = ThemeImagePicker(keyPath: imageName)
        viewController.tabBarItem.theme_selectedImage = ThemeImagePicker(keyPath: SelectedImageName, map: { (imageName) -> UIImage? in
            return UIImage(named: (imageName as? String ?? ""))?.withRenderingMode(.alwaysOriginal)
        })
        
        viewController.title = title
        let navigationController = UINavigationController(rootViewController: viewController)
        addChild(navigationController)
    }
}

// MARK: - XGTabBar

private class XGTabBar: UITabBar
{
    override init(frame: CGRect)
    {
        super.init(frame: frame)

        addSubview(publishButton)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 发布按钮
    private lazy var publishButton: UIButton = {
        let button = UIButton(type: .custom)
        button.theme_setImage("images.tabBar_publish_normal", forState: .normal)
        button.sizeToFit()
        return button
    }()
        
    // 子控件布局
    override func layoutSubviews()
    {
        super.layoutSubviews()
        
        var index = 0
        let width = floor(bounds.width / 5.0)
        let height: CGFloat = 49.0
        publishButton.center = CGPoint(x: bounds.width * 0.5, y: height * 0.5)
        for view in subviews {
            if view.isMember(of: NSClassFromString("UITabBarButton")!) {
                view.frame = CGRect(x: CGFloat(index > 1 ? index + 1 : index) * width, y: 0, width: width, height: height)
                index += 1
            }
        }
    }
}
